<?php
	$content = file_get_contents("php://input");
	$tblinput = json_decode($content);	
	$tbl = $tblinput->data;
	//echo var_dump($content);
	
	$f = "=".$_REQUEST['fname'];
	preg_match('~=(.*?).php~', $f, $filename);
	$filename = $filename[1]."_export.csv";	
	//echo $filename;
	
	preg_match_all('~"ng-binding">(.*?)</td>~', $tbl, $data);	
	preg_match_all('~<th>(.*?)</th>~', $tbl, $heading);	
	//echo var_dump($data)."<br>-----------------<br>".var_dump($heading);
	
	$h = $heading[1];	
	for($i=0;$i<sizeof($heading[1]);$i++)
	{		
		$title = $h[$i].",,";
		$csv_hdr = $csv_hdr.preg_replace('~<(.*?)>~', '', $title);			
	}
	
	$d = $data[1];
	$count = 0;
	for($i=0;$i<sizeof($data[1]);$i++)
	{				
		$d2 = preg_replace('~</h(.)>~', '', $d[$i],-1);
		//$row = $d[$i].",,";					
		$row = $d2.",,";					
		if($count == sizeof($heading[1]))
		{
			$row = "+".$row;			
			$count = 0;
		}					
		$csv_body=$csv_body.$row;
		$count++;		
	}
	
	$csv_body2 = explode("+", $csv_body);
	
	//var_dump($csv_body2);
	//var_dump($hdr);
	
	header( 'Content-Type: text/csv' );
    header( 'Content-Disposition: attachment;filename='.$filename);
    $fp = fopen('php://output', 'w');			
	fputcsv($fp, explode(",,", $csv_hdr));
	fwrite($fp, PHP_EOL);
	for($i=0;$i<sizeof($csv_body2);$i++)			
		fputcsv($fp, explode(",,",$csv_body2[$i]));							
	fclose($fp);
	
?> 